<style>
	.simditor-body {
	    height: 400px;
	    overflow: auto;
	}
	.publish {
        width: 100%;
        height: 100%;
        position: fixed;
        top: 50px;
        padding-left: 150px;
        left: 0;
        z-index: 9999;
        background-color: #fff;
    }
    .ivu-upload-list {
    	margin-top: 0;
    }
    .mini-editor {
    	width: 650px;
    }
    .mini-editor .simditor-body {
	    height: 100px;
	    overflow: auto;
	}
    
    /**/
   .diy-content {
   	background-color: #fafafa;
   	border-radius: 4px;
   	margin-top: -10px;
   	margin-bottom: 14px;
   }
   .diy-content > .ivu-form-item {
   	padding-top: 10px;
   	padding-bottom: 10px;    
   	margin-top: 0;
   	margin-bottom: 0;
   }
</style>
<template>
<div class="publish">
    <header class="admin-container-header clearfix">
        <div class="header-group">
            <h4 class="title">
                <Button type="text" size='small' style="position: relative;top: -1px;" @click='articlePublishBack'><Icon type="ios-arrow-back" size='20' /></Button>
                <span class="text">内容</span>
            </h4>
            <h5 class="sub-title">{{itemPublishId? "编辑" : "发布"}}</h5>
        </div>
        <div class="float-right">
            <button type="button" class="float-right ivu-btn ivu-btn-primary ivu-btn-circle" @click='publishPost'>
                <span><Icon type="md-checkmark" /> 提交保存</span>
            </button>
        </div>
    </header>
    <main class="admin-container-body" style="height: calc(100% - 62px)">
        <section class="">
            <section class="panel-box">
                <section class="panel-box-body">
                     <i-Form :label-width="80" class="mb-3 v-h" :class='vShow'>
						                	
			                        <Form-Item label="标题" class="ivu-form-item-required">
			                            <i-Input style="width: 500px;" v-model="title" placeholder="请输入标题..."></i-Input>
			                        </Form-Item>
			                        <Form-Item label="栏目" class="ivu-form-item-required">
			                            <Cascader :data="categoryList" transfer v-model="cidArray" :clearable="false" style="width: 500px;"></Cascader>
			                        </Form-Item> 
			                         <Form-Item label="描述">
			                            <i-Input type="textarea" style="width: 500px;" v-model="description" placeholder="请输入描述..."></i-Input>
			                        </Form-Item>
			                        <Form-Item label="关键词">
			                            <i-Input type="textarea" style="width: 500px;" v-model="keywords" placeholder="请输入关键词..."></i-Input>
			                        </Form-Item>
			                        <Form-Item label="浏览">
			                            <InputNumber style="width: 500px;" v-model="views"></InputNumber>
			                        </Form-Item>
			                        <Form-Item label="封面">
			                            <i-Input style="width: 500px;" v-model="imgUrl" placeholder="缩略图可以直接添加链接">
			                                <Upload slot="append"  :show-upload-list='false' :headers='uploadHeaders' :data='uploadData' :on-success="handleSuccessImg" :format="['jpg','png','gif','jpeg']" name='fileDataFileName'
			                                    :action="uploadUrl">
			                                    <Button  icon="ios-cloud-upload-outline">上传缩略图</Button>
			                                </Upload>
			                            </i-Input>
			                        </Form-Item>
			                        <div class="diy-content" v-if='fieldList.length'>
				                        <Form-Item v-if='fieldList.length' v-for='(item,index) in fieldList' :label="item.title" >
				                            <Input v-if='item.style == "" || item.style == "input"' v-model="item.value" style="width: 500px;"></Input>
				                            <div style="position: relative;">
					                          	<Input v-if='item.style == "upload"' style="width: 500px;" v-model="item.value"></Input>
				                                <Upload style='position: absolute;left: 510px;top: 0px;'  v-if='item.style == "upload"' :data='{paramId:index,paramField:item.field}' :show-upload-list='false' :on-success="handleSuccessFile" :format="['jpg','png','gif','zip','rar']" name='fileDataFileName' action="{$domain}/article/ApiAdminArticleUpload/defaultUpload">
				                                    <Button icon="ios-cloud-upload-outline">上传</Button>
				                                </Upload>
				                            </div>
				                            <RadioGroup v-if='item.style == "radio"' v-model="item.value"><Radio v-for='(sub,sIndex) in item.data' :label="sub"></Radio></RadioGroup>
				                            <!--<CheckboxGroup v-if='item.style == "checkbox"' v-model="item.valueArray"><Checkbox v-for='sub in item.data' :label="sub"></Checkbox></CheckboxGroup>-->
				                            <Select v-if='item.style == "select"' transfer v-model='item.value' style="width: 500px;"><Option v-for='(sub,sIndex) in item.data' :value="sub" :key='sub'>{{sub}}</Option></Select>
				                            <DatePicker v-if='item.style == "date"' type="date" v-model='item.value' placeholder="请选择日期" style="width: 200px"></DatePicker>
				                            <Input v-if='item.style == "textarea"' type='textarea' v-model="item.value" style="width: 500px;"></Input>
				                        	<InputNumber v-if='item.style == "int" || item.style == "decimal"' :min="0" v-model="item.value"></InputNumber>
			                        		<div class="mini-editor" v-if='item.style == "edit"'>
                								<textarea class="form-control" :id='"mini_" + item.field' rows="3" placeholder=""></textarea>
                							</div>
				                        </Form-Item>
			                        </div>
						
                        {if condition='$addInfo.superSite'}
                        <Form-item label="站点" :label-width="80">
                             <Select transfer v-model='siteId' style="width: 300px;">
                                <Option v-for='(sub,sIndex) in siteList' :value="sub.id" :key='sub.id'>{{sub.domain}}</Option>
                             </Select>
                        </Form-item>
                        {/if}
                        <Form-Item label="标签" prop="title">
                            <div class="m-b-sm">
                                <i-Input v-model='tagName' style="width: 300px;"  placeholder="请选择标签,或直接输入回车即可"  @on-blur='timeShowList' @on-focus='tagsSearch' @on-change='tagsSearch' @on-click="tagsClick($event)" @on-keyup="enterTags($event)">
                                     <i-Button slot="append" class="tags-btn" @click='btnTags'><Icon type="md-checkmark" /></i-Button>
                                </i-Input>
                                <div class="ivu-select-dropdown ivu-auto-complete" v-show='isShowTagsList' style="width: 300px;">
                                    <ul class="ivu-select-dropdown-list">
                                        <li class="ivu-select-item" v-for="item in tagsList" :value="item" :key="item" @click='tagsClick(item)'>{{item}}</li>
                                    </ul>
                                </div>
                            </div>
                            <Tag class='m-t-xs' closable v-for="item in selectedTagsList" :key="item" :name='item' @on-close="selectedTagsListClose">{{item}}</Tag>
                        </Form-Item> 
	                        <Form-Item label="内容" class="ivu-form-item-required">
	                            <textarea id="article_editor" class="simditor" style="height: 400px;" placeholder="请输入内容..."></textarea>
	                        </Form-Item>
			             
			            </Tabs>
                    </i-Form>
                    <Spin size="large" fix v-if="spinShow"></Spin>
                    <div class="text-center mb-5">
                        <button type="button" class="ivu-btn ivu-btn-primary ivu-btn-circle" @click='publishPost'>
                            <span><Icon type="checkmark-round"></Icon> 提交保存</span>
                        </button>
                    </div>
                </section>
            </section>
        </section>
    </main>
    
</div>
</template>

<script>
export default {
    props: {
        itemPublishId: String,
        itemPublishCid: String,
        itemPublishSiteId: String,
    },
     data () {
       return {
            vShow: '',
            spinShow: true,
            uuid: '',
            title: '',
            keywords: '',
            description: '',
            link_tags: '',
            categoryList: [],
            cid: '',
            cidArray: [],
            is_recommend: '',
            content: '',
            url_name: '',
            
            fieldList: [],
            
            ruleValidate: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
                ],
            },
            
            tagsList: [],
            tagsListDefault: [],
            tagName: '',
            selectedTagsList: [], //已选中的标签列表
            isShowTagsList: false, //标签下拉状态
            toolbar : ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', '|', 'ol', 'ul', 'blockquote', 'code', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent', 'alignment', 'html'],
            uploadUrl: '',
            uploadHeaders: {
                dataid: ''
            },
            uploadData: {
                type: 'article',
                key: '',
                siteId: '',
            },
            views: 0,
            imgUrl: '',
            itemInfo: '',
            categoryInfo: {},
            itemTabsValue: 'default',
       }
     },
    watch: {
        cidArray() {
            if (this.cidArray) {
                this.getFieldList();
            }
        },
    },
    mounted() {
        if (this.itemPublishCid) {
            this.cid = this.itemPublishCid;
        } else {
            this.cid = 1;
        }
        
        this.editorInit();
    },
    methods: {
        getFieldList() {
            tempCid = this.cidArray[this.cidArray.length - 1];
            for (var i = 0; i < this.categoryList.length; i++) {
                if (this.categoryList[i]['id'] == tempCid) {
                    this.categoryInfo = this.categoryList[i];
                }
                if (this.categoryList[i].children && this.categoryList[i].children.length) {
                    for (var g = 0; g < this.categoryList[i].children.length; g++) {
                        if (tempCid == this.categoryList[i].children[g].id) {
                            this.categoryInfo = this.categoryList[i].children[g];
                        }
                    }
                }
            }
            if (!this.categoryInfo) {
                return false;
            }
            this.$ssy.ajax('{$domain}/article/ApiAdminArticleField/itemList', {
                modelName: this.categoryInfo.model_name ? this.categoryInfo.model_name : 'news',
            }).then(res => {
                if (res.code == 1) {
                    var fieldList = res.data;
                    var tempFieldList = [];
                    if (fieldList) {
                        for (var i = 0; i < fieldList.length; i++) {
                            fieldList[i]['value'] = '';
                            fieldList[i]['editor'] = '';
                            if (fieldList[i]['style'] == "decimal") {
                            	fieldList[i]['value'] = 0;
                            }
                            if (fieldList[i]['style'] == 'date') {
                            	fieldList[i]['value'] = new Date();
                            }
                            if (fieldList[i]['style'] == "checkbox") {
                            	fieldList[i]['valueArray'] = [];
                            }
                        }
                    }
                    if (this.itemInfo) {
                        for(var i = 0; i < fieldList.length; i++) {
                            fieldList[i].value = this.itemInfo[fieldList[i].field];
            				if (fieldList[i]['style'] == 'date') {
            					var tempDate = this.itemInfo[fieldList[i].field];
            					var timestamp = Date.parse(tempDate);
                            	fieldList[i]['value'] = new Date(timestamp);
                            }
                        }
                    }
                   this.fieldList = fieldList;
                    if (!this.itemInfo) {
	                    if (this.fieldList) {
	                        for (var i = 0; i < this.fieldList.length; i++) {
	                        	if (this.fieldList[i]['style'] == "edit") {
							        var _this = this;
							        var editField = this.fieldList[i]['field'];
							        setTimeout(function() {
							    		_this.createMiniEditor('mini_' + editField,editField);
							        }, 300);
	                            }
	                        }
                    	}
                    }
                            
                   
                }
            });
        },
        handleSuccessFile(res) {
        	if (res.code == 1) {
           		this.fieldList[res.data.paramId]['value'] = res.data.url;
        	}
        },
        handleSuccessImg(res) {
           this.imgUrl = res.data;
        },
        editorInit() {
            var _this = this;
            setTimeout(function() {
                _this.createEditor();
            }, 100);
        },
        //创建编辑器
       createMiniEditor: function(editId,editField) {
            var _this = this;
            var editor = new Simditor({
                textarea: document.getElementById(editId),
                toolbar: _this.toolbar,
                upload: {
                    url: '{$domain}/setting/ApiAdminUpload/defaultImgUpload',
                    params: {
                        type: 'article',
                    },
                    fileKey: 'fileDataFileName',
                    connectionCount: 3,
                    leaveConfirm: '正在上传文件'
                },
                pasteImage: true,
            });
            if (this.itemInfo) {
            	editor.setValue(this.itemInfo[editField]);
            } else {
            	editor.setValue('');
            }
            if (this.fieldList) {
                for (var i = 0; i < this.fieldList.length; i++) {
                	if (this.fieldList[i]['style'] == "edit") {
				        if (this.fieldList[i]['field'] == editField) {
				        	this.fieldList[i]['editor'] = editor;
				        }
                    }
                }
        	}
        },
        createEditor() {
            var _this = this;
            this.uploadUrl = '{$domain}/setting/ApiAdminUpload/defaultImgUpload';
            this.uploadHeaders.dataid = this.$route.params.dataId ? this.$route.params.dataId : "";
            this.uploadData.key = '';
            document.getElementById('article_editor').innerHTML = '';
            this.editor = new Simditor({
                textarea: document.getElementById('article_editor'),
                toolbar: _this.toolbar,
                upload: {
                    url: this.uploadUrl,
                    params: {
                        type: 'article',
                    },
                    fileKey: 'fileDataFileName',
                    connectionCount: 3,
                    leaveConfirm: '正在上传文件'
                },
                pasteImage: true,
                autosave: 'editor-content'
            });
            this.vShow = 'v-s';
            this.spinShow = false;
            
            this.getCategoryList();
        },
        getCategoryList: function() {
            var _this = this;
            this.$ssy.ajax('{$domain}/article/ApiAdminArticleCategory/categoryList', {
                
            }).then(res => {
                if(res.code == 1) {
                    var tempCategoryList = res.data.categoryList;
                    var categoryList = [];
                    if (tempCategoryList) {
                        for (var i = 0; i < tempCategoryList.length; i++) {
                        	if (tempCategoryList[i]['model_name'] != 'page') {
                        		categoryList.push(tempCategoryList[i]);
                        	}
                        }
                    }
                    if (this.cid) {
                        var tempCidArray = [];
                        for (var i = 0; i < categoryList.length; i++) {
                            if (this.cid == categoryList[i].id) {
                                tempCidArray.push(categoryList[i].id);
                            } else {
                                if (categoryList[i].children && categoryList[i].children.length) {
                                    for (var g = 0; g < categoryList[i].children.length; g++) {
                                        if (this.cid == categoryList[i].children[g].id) {
                                            tempCidArray.push(categoryList[i].id);
                                            tempCidArray.push(categoryList[i].children[g].id);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    this.categoryList = categoryList;
                    if (this.itemPublishId) {
                        this.getItemInfo(tempCidArray);
                    } else {
                    	this.cidArray = tempCidArray;
                    }
                }
            });
        },
        //编辑时
        getItemInfo(tempCidArray) {
            this.$ssy.ajax('{$domain}/article/ApiAdminArticle/itemInfo', {
                id: this.itemPublishId,
            }).then(res => {
                if(res.code == 1) {
                    var itemInfo = res.data;
                    this.keywords = itemInfo.keywords;
                    this.description = itemInfo.description;
                    this.link_tags = itemInfo.link_tags;
                    this.uuid = itemInfo.uuid;
                    this.title = itemInfo.title;
                    this.url_name = itemInfo.url_name;
                    this.views = itemInfo.views;
                    this.cid = itemInfo.cid;
                    this.imgUrl = itemInfo.img_url;
                    this.is_recommend = itemInfo.is_recommend == 0 ? false : true;
                    this.tags = [];
                    this.publish_time = itemInfo.publish_time ? new Date(parseInt(itemInfo.publish_time) * 1000) : '';
                    this.itemInfo = itemInfo;
                    this.editor.setValue(itemInfo.content);
                 	this.getItemTags(itemInfo.uuid);
                   	this.cidArray = tempCidArray;
                }
            });
        },
        getItemTags: function(itemId) {
            this.$ssy.ajax('{$domain}/tag/ApiAdminTagsRel/itemList', {
                'itemType': 'article',
                'itemId': itemId,
            }).then(res => {
                if(res.code == 1) {
                    var tagsList = res.data.itemList;
                    if (tagsList) {
                        if(tagsList.length > 0) {
                            for(var i = 0; i < tagsList.length; i++) {
                                tagsList[i].title = tagsList[i].tags.title;
                                this.selectedTagsList.push(tagsList[i].title);
                            }
                        }
                    }
                }
            });
        },
        //开始发布
        publishPost: function(param) {
            this.content = this.editor.getValue();
            var timestamp = Date.parse(this.publish_time);
            timestamp = timestamp / 1000;
            var fieldList = [];
            if (this.fieldList) {
            	for (var i = 0; i < this.fieldList.length; i++) {
            		fieldList[i] = this.fieldList[i];
            	}
            }
            if (fieldList) {
            	for (var i = 0; i < fieldList.length; i++) {
            		if (fieldList[i]['style'] == 'date') {
            			fieldList[i]['value'] = formatDate(Date.parse(fieldList[i]['value']), 'yyyy-mm-dd');
            		}
            		if (fieldList[i]['style'] == 'edit') {
            			fieldList[i]['value'] = fieldList[i]['editor'].getValue();
            			fieldList[i]['editor'] = '';
            		}
            	}
            }
            if(this.itemPublishId) {
                this.$ssy.ajax('{$domain}/article/ApiAdminArticle/itemEdit', {
                    uuid: this.uuid,
                    title: this.title,
                    keywords: this.keywords,
                    description: this.description,
                    link_tags:this.link_tags,
                    url_name: this.url_name,
                    views: this.views,
                    content: this.content,
                    cid: this.cidArray[this.cidArray.length - 1],
                    is_recommend: this.is_recommend ? '1' : '0',
                    tags: this.selectedTagsList.join(','),
                    publish_time: timestamp ? timestamp : '',
                    fieldList: JSON.stringify(fieldList),
                    img_url : this.imgUrl,
                    modelName: this.categoryInfo.model_name ? this.categoryInfo.model_name : 'news',
                }).then(res => {
                    if(res.code == 1) {
                        this.$Message.success(res.msg);
                        this.editor.setValue('');
                        this.articlePublishBack();
                    }
                });
            } else {
                var tempField = this.fieldList;
                this.$ssy.ajax('{$domain}/article/ApiAdminArticle/itemAdd', {
                    title: this.title,
                    keywords: this.keywords,
                    description: this.description,
                    link_tags:this.link_tags,
                    url_name: this.url_name,
                    views: this.views,
                    content: this.content,
                    cid: this.cidArray[this.cidArray.length - 1],
                    is_recommend: this.is_recommend ? '1' : '0',
                    tags: this.selectedTagsList.join(','),
                    publish_time: timestamp ? timestamp : '',
                    fieldList: JSON.stringify(tempField),
                    img_url : this.imgUrl,
                    modelName: this.categoryInfo.model_name ? this.categoryInfo.model_name : 'news',
                }).then(res => {
                    if(res.code == 1) {
                        if(res.data) {
                            var resMIp = JSON.parse(res.data);
                            this.$Message.success('推送成功：' + resMIp.success_mip + '条，当天剩余条数：' + resMIp.remain_mip);
                        }
                        this.editor.setValue('');
                        this.$Message.success(res.msg);
                        this.articlePublishBack();
                    }
                });
            }

        },
        //关闭当前发布弹出层
        articlePublishBack() {
            if(this.editor.getValue()) {
                this.$emit('itemPublishValue', 'close');
            } else {
                this.$emit('itemPublishValue', 'closePublish');
            }
        },
        
        getTags() {
            this.$ssy.ajax('{$domain}/tag/ApiAdminTag/itemList', {
                limit: 10,
                orderBy: 'relevance_num',
                keywords: this.tagName,
            }).then(res => {
                if(res.code == 1) {
                    var tagsList = res.data.itemList;
                    this.isShowTagsList = true;
                    this.tagsList = [];
                    if (tagsList.length) {
                        for (var i = 0; i < tagsList.length; i++) {
                            this.tagsList.push(tagsList[i].title);
                        }
                    } else {
                        this.isShowTagsList = false;
                    }
                }
            });
        },
        //tags搜索
        tagsSearch() {
            this.getTags();
        },
        //tags按钮确认
        btnTags: function() {
            if (this.tagName) {
                //支持,号空格分割
                var tempSubTagName = this.tagName.split(',');
                if (tempSubTagName) {
                    for (var j = 0; j < tempSubTagName.length; j++) {
                        if (tempSubTagName[j]) {
                            if (this.selectedTagsList.indexOf(tempSubTagName[j]) == -1) {
                                this.selectedTagsList.push(tempSubTagName[j]);
                            }
                        }
                    }     
                                
                }
                this.tagName = '';
                this.isShowTagsList = false;
            }
        },
        enterTags: function(ev) {
            if(ev.keyCode == 13) {
                this.btnTags();
            }
        },
        timeShowList() {
            var _this = this;
            setTimeout(function() {
                _this.isShowTagsList = false;
            },200)
        },
        tagsClick(val) {
            if (this.selectedTagsList.indexOf(val) == -1) {
                this.selectedTagsList.push(val);
            }
            this.tagName = '';
            this.isShowTagsList = false;
        },
        selectedTagsListClose(event, name) {
            const index = this.selectedTagsList.indexOf(name);
            this.selectedTagsList.splice(index, 1);
        },
    }
}
</script>
